// import { routers } from '@/router';
import { getRouters } from '@/api/login';
import store from '@/store'
import Layout from '@/layout'

const permission = {
  state: {
    routes: [],
    navs: []
  },
  mutations: {
    SET_ROUTES: (state, routes = []) => {
      state.routes = routes;
    },
    SET_NAVS: (state, navs = []) => {
      state.navs = navs;
    }
  },
  actions: {
    GenerateRoutes({ commit }) {
      const roles = store.getters.roles;
      return new Promise((resolve, reject) => {
        getRouters({ roles: roles.join() })
          .then((res) => {
            commit('SET_ROUTES', res.data.tree);
            commit('SET_NAVS', res.data.routers);
            const rewriteRoutes = filterAsyncRouter(res.data.routers);
            resolve(rewriteRoutes);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    ClearPermission({ commit }) {
      commit('SET_ROUTES', []);
      commit('SET_NAVS', []);
    }
  }
}

function filterAsyncRouter(routes) {
  let routerObj = [];
  for (let i = 0; i < routes.length; i++) {
    let url = routes[i].url;
    if (routes[i].parent) {
      let target = routes.find(r => r.key === routes[i].parent);
      url = target.url + routes[i].url
    }
    if (!routes[i].children.length) {
      routerObj.push({
        path: '',
        component: Layout,
        children: [
          {
            path: url,
            component: (resolve) => require([`@/views/${routes[i].path}`], resolve)
          }
        ]
      })
    }
  }
  return routerObj;
}

// const routesOrder = function (routes) {
//   if (!routes.length) {
//     return routes;
//   }
//   routes.sort((a, b) => {
//     return a.sort - b.sort;
//   })
//   for (let i = 0; i < routes.length; i++) {
//     routesOrder(routes[i].children);
//   }
//   return routes;
// }

export default permission;